package niuke;

/**
 * description:
 * author:zt
 * date:2021-08-09
 */

/**
 *
 给定head链表1->2->3->4->5, 重新排列为 1->5>2->4->3
 给定head链表1->2->3->4, 重新排列为 1->4->2->3
 */
public class NC2 {
    public void reorderList(ListNode head) {
        if (head == null) return;

        ListNode fast = head, slow = head;
        while (fast.next!=null && fast.next.next!=null){
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode nHead = slow.next;
        slow.next = null;
        ListNode h = reverse(nHead);

        mergeList(head,h);
    }

    public void mergeList(ListNode l1, ListNode l2) {
        ListNode l1_tmp;
        ListNode l2_tmp;
        while (l1 != null && l2 != null) {
            l1_tmp = l1.next;
            l2_tmp = l2.next;

            l1.next = l2;
            l1 = l1_tmp;

            l2.next = l1;
            l2 = l2_tmp;
        }
    }
    public ListNode reverse(ListNode head){
        ListNode pre = null;
        ListNode cur = head;
        while (cur!=null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}
